package com.hue.concurrent.day04;

/*
    线程饥饿:
        一个线程的优先级很低，始终得不到cpu的调度
 */
public class Demo06 {
    public static void main(String[] args) {
        Object a = new Object();
        Object b = new Object();
        Object c = new Object();
        Object d = new Object();
        Object e = new Object();
        new People(a, b,0).start();
        new People(b, c,1).start();
        new People(c, d,2).start();
        new People(d, e,3).start();
        new People(a, e,4).start();
    }

    public static class People extends Thread {
        private final Object left;
        private final Object right;

        public People(Object left, Object right, int id) {
            super(Name.get(id).getName());
            this.left = left;
            this.right = right;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (left) {
                    synchronized (right) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + "开始吃饭...");
                    }
                }
            }
        }
    }

    public static enum Name {
        ONE("张三"), TWO("李四"), THREE("王五"), FOUR("钱六"), FIVE("田七");

        private String name;

        Name(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public static Name get(int i) {
            Name[] names = Name.values();
            return names[i];
        }
    }
}
